package cn.semes.org.service.impl;

import cn.semes.aop.LogAop;
import cn.semes.basic.mapper.BaseMapper;
import cn.semes.basic.query.BaseQuery;
import cn.semes.basic.service.impl.BaseServiceImpl;
import cn.semes.basic.util.PageList;
import cn.semes.org.domain.Department;
import cn.semes.org.domain.Employee;
import cn.semes.org.mapper.DepartmentMapper;
import cn.semes.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService{
    @Autowired
    private DepartmentMapper mapper;

@LogAop
    @Override
    public Department findById(Long id) {
        return mapper.findById(id);
    }

    @LogAop
    @Override
    public List<Department> findAll() {
        return mapper.findAll();
    }

    @LogAop
    @Override
    public void add(Department t) {

        mapper.add(t);
    }

    @LogAop
    @Override
    public void update(Department t) {
        mapper.update(t);
    }

    @LogAop
    @Override
    public void delete(Long id) {
        mapper.delete(id);
    }

    @LogAop
    @Override
    public void batchDelete(List<Long> ids) {
        mapper.batchDelete(ids);
    }

    @LogAop
    @Override
    public PageList<Department> queryByPage(BaseQuery query) {
        Integer totals = mapper.queryByCount(query);
        if (null == totals || 0 == totals){
            return new PageList<Department>(0,new ArrayList<>());
        }
        // 查询数据
        List<Department> rows = mapper.queryByPage(query);
        return new PageList<Department>(totals,rows);
    }
    
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @LogAop
    public List<Department> findDeptTree() {
        List<Department> result = new ArrayList<>();
        // 查询出所有的数据
        List<Department> allDepartments = departmentMapper.findAll();
        // 将 全部的部门数据 转成map key  value
        Map<Long, Department> deptMap = allDepartments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));

        for (Department dept : allDepartments) {
            if (null == dept.getParentId()){
                // 这就是一级数据
                result.add(dept);
            }else {
                // 中间级不能有null否则报错，建议都tama判空，日
                Department parent = deptMap.get(dept.getParentId());
                    parent.getChildren().add(dept);
            }
        }
        return result;

    }

    @Override
    public List<Employee> findByDeptId(Long id) {
       return departmentMapper.findByDeptId(id);
    }
}
